package com.lw.leetcode.arr.a;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 2373. 矩阵中的局部最大值
 *
 * @author liw
 * @version 1.0
 * @date 2022/8/15 10:15
 */
public class LargestLocal {

    public static void main(String[] args) {
        LargestLocal test = new LargestLocal();

        // [[9,9],[8,6]]
//        int[][] arr = {{9,9,8,1},{5,6,2,6},{8,2,6,4},{6,2,2,2}};

        //
        int[][] arr = {{20, 8, 20, 6, 16, 16, 7, 16, 8, 10}, {12, 15, 13, 10, 20, 9, 6, 18, 17, 6}, {12, 4, 10, 13, 20, 11, 15, 5, 17, 1}, {7, 10, 14, 14, 16, 5, 1, 7, 3, 11}, {16, 2, 9, 15, 9, 8, 6, 1, 7, 15}, {18, 15, 18, 8, 12, 17, 19, 7, 7, 8}, {19, 11, 15, 16, 1, 3, 7, 4, 7, 11}, {11, 6, 5, 14, 12, 18, 3, 20, 14, 6}, {4, 4, 19, 6, 17, 12, 8, 8, 18, 8}, {19, 15, 14, 11, 11, 13, 12, 6, 16, 19}};

        int[][] ints = test.largestLocal(arr);
        for (int[] anInt : ints) {
            System.out.println(Arrays.toString(anInt));
        }
    }

    public int[][] largestLocal(int[][] grid) {
        int m = grid.length - 2;
        int n = grid[0].length - 2;
        int[][] arr = new int[m][n];
        int[] count = new int[101];
        for (int i = 0; i < m; i++) {
            Arrays.fill(count, 0);
            for (int j = i; j < i + 3; j++) {
                for (int k = 0; k < 3; k++) {
                    count[grid[j][k]]++;
                }
            }
            arr[i][0] = getMax(count);
            for (int j = 1; j < n; j++) {
                count[grid[i][j - 1]]--;
                count[grid[i][j + 2]]++;
                count[grid[i + 1][j - 1]]--;
                count[grid[i + 1][j + 2]]++;
                count[grid[i + 2][j - 1]]--;
                count[grid[i + 2][j + 2]]++;
                arr[i][j] = getMax(count);
            }
        }
        return arr;
    }

    private int getMax(int[] count) {
        for (int i = count.length - 1; i >= 0; i--) {
            if (count[i] != 0) {
                return i;
            }
        }
        return 0;
    }

}
